package com.changgou.controller;


import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.util.FastDFSClient;
import com.changgou.util.FastDFSFile;
import jdk.net.SocketFlow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


@RestController
@RequestMapping("/file")
public class FileController {

    private Logger log = LoggerFactory.getLogger(getClass());

    @PostMapping("/upload")
    public Result upload(@RequestParam("file")MultipartFile multipartFile){

        try {
            String filename = multipartFile.getOriginalFilename();
            log.info("文件名称: {}",filename);
            byte[] bytes = multipartFile.getBytes();
            String ext = filename.substring(filename.lastIndexOf("."));
            log.info("文件拓展名: {}",ext);
            FastDFSFile fastDFSFile = new FastDFSFile(filename,bytes,ext);
            String[] upload = FastDFSClient.upload(fastDFSFile);

            //获取组名
            String groupName = upload[0];
            log.info("组名: {}",groupName);
            //获取文件存储路径
            String remoteFileName = upload[1];
            log.info("文件存储路径: {}",remoteFileName);

            String filePath = FastDFSClient.getTrackerUrl() + groupName + "/" + remoteFileName;
            log.info("文件上传后完整请求路径: {}",filePath);

            return new Result();
        } catch (IOException e) {
            log.info("文件上传异常:   {}" + e);
            return new Result(false, StatusCode.ERROR,"文件上传异常");
        }

    }

}
